from util import json, db, route, Page

bp = route(__name__)

@bp.get("/")
async def index(request):
    return json({})

@bp.get("/<id:int>")
async def id(request, id=1):
    params = {
        'id': id
    }
    res = db.query('SELECT a.*, b.nickname,b.account,b.avatar FROM tweet AS a INNER JOIN user AS b ON a.uid = b.id where b.id=:id limit 0,1', **params).one()
    return json(res.as_dict())

@bp.get("/info/<id:int>")
async def info(request, id=1):
    params = {
        'id': id
    }
    res = db.query('SELECT a.*, b.nickname,b.account,b.avatar FROM tweet AS a INNER JOIN user AS b ON a.uid = b.id where a.id=:id limit 0,1', **params).one()
    return json(res.as_dict())


@bp.get("/tweet/<page:int>")
async def tweet(request, page=1):
    params = {
        'page': page,
        'limit': 10,
        'uid': request.args.get('uid')
    }

    typeMap = ''
    type = request.args.get('type')
    if type is None:
        pass
    else:
        typeMap = "and a.type = '%s' " %(type)

    # 生成页数
    params['page'] = Page(params['page'], params['limit'])
    sql = 'SELECT a.*, b.nickname,b.account,b.avatar FROM tweet AS a INNER JOIN user AS b ON a.uid = b.id where a.uid=:uid '+typeMap+'  ORDER BY update_date asc LIMIT :page,:limit'
    res = db.query(sql, **params)
    return json(res.as_dict())
